<template>
  <div id="circuitPreview" ref="circuitPreviewRef" @mousemove="circuitMouseMove">
    <a-spin :spinning="spinning">
      <div class="layout" id="homePage">
        <div
          class="svg-contain"
          id="screen"
          :style="{
            'background-image': infoWaterTemplateVo.bgImg.type != 'default' ? `url(${infoWaterTemplateVo.bgImg.base64Data})` : '',
            backgroundColor: infoWaterTemplateVo.bgImg.type == 'default' ? '#000000' : '',
            width: $store.state.windowAttributes.absoluteWidth + 'px',
            height: $store.state.windowAttributes.absoluteHeight + 'px',
          }"
          v-if="infoWaterTemplateVo.waterTemplateInfo.length"
        >
          <svg
            version="1.1"
            xmlns="http://www.w3.org/2000/svg"
            xmlns:xlink="http://www.w3.org/1999/xlink"
            preserveAspectRatio="xMinYMin meet"
            class="svgContent"
            @dblclick="clearSelectSvgInfo"
            viewBox="0,0,1920,1080"
          >
            <defs />
            <g
              v-for="(item, index) in infoWaterTemplateVo.waterTemplateInfo"
              :key="item"
              :id="item.componentDataId"
              :title="item.title"
              :transform="
                'translate(' +
                item.svgPositionX +
                ',' +
                item.svgPositionY +
                ')' +
                'rotate(' +
                item.angle +
                ')' +
                'scale(' +
                item.size +
                ')'
              "
              :class="[selectSvgInfo.componentDataId == item.componentDataId ? 'topo-layer-view-selected' : '', 'cursor']"
              @mouseenter="mouseoverSvg($event, index)"
              @mouseleave="clearSelectSvgInfo"
            >
              <register-components :component_prop="item" :svgInfoData="infoWaterTemplateVo.waterTemplateInfo" />
            </g>
          </svg>
        </div>
      </div>
    </a-spin>
    <a-empty
      class="emptyCenter"
      v-if="!this.addressSelecter?.length || !infoWaterTemplateVo.waterTemplateInfo.length"
      description="暂无相关数据"
    />
    <div v-if="isShowBackButton == '1'" class="btns-content">
      <a-button type="primary" @click="returnRouter">返回</a-button>
    </div>
    <!--地址选择框-->
    <div v-if="isShowSelect == '1'" class="selectAddress">
      <a-select
        v-model:value="selectAddress"
        style="min-width: 120px"
        :getPopupContainer="(triggerNode) => triggerNode.parentNode"
        :dropdownMatchSelectWidth="false"
        @change="changeSelect"
        option-label-prop="children"
        placeholder="请选择地址"
      >
        <a-select-option v-for="item in addressSelecter" :key="item" :value="item.deviceAreaId" :label="item.equipmentName">
          {{ item.equipmentName }}
        </a-select-option>
      </a-select>
    </div>
    <div class="screen" id="iconScreen" v-if="infoWaterTemplateVo.waterTemplateInfo.length" @click="fullScreenEvent">
      <div v-if="isScreenFull">
        <fullscreen-exit-outlined />
      </div>
      <div v-else>
        <fullscreen-outlined />
      </div>
    </div>
    <!--详情框-->
    <div ref="componentInfoModal" v-show="showComponentInfoModal" class="componentInfoModal">
      <div class="title">{{ selectSvgInfo.componentData?.title }}</div>
      <div v-for="(item, index) in selectSvgInfo.keyData" :key="index">
        <div v-if="item.dataType == 1">{{ item?.keyName }}：{{ Number(item.value) ? '开' : '关' }}</div>
        <div v-else-if="item?.dataType && item?.dataType != 1">
          {{ item?.keyName }}：{{ item?.value + ' ' + (item?.unit || '') }}
        </div>
        <div v-if="item?.remark">备注：{{ item?.remark || '' }}</div>
      </div>
    </div>
  </div>
</template>
<script>
import { Storage } from '@/util/storage.js'
import { FullscreenExitOutlined, FullscreenOutlined } from '@ant-design/icons-vue'
import registerComponents from '@/components/svgComponents/registerComponents.vue'
import screenfull from 'screenfull'
import { websocketTemplateVoucher, infoTemplate, getMachineRoomList, machineRoomTemplateRendering } from '@/network/api/index'
import { fullScreen } from '@/util/index'
import { message } from 'ant-design-vue'
import CWebSocket from '@/util/CWebscoket'
export default {
  components: {
    registerComponents,
    FullscreenExitOutlined,
    FullscreenOutlined,
  },
  data() {
    return {
      isScreenFull: Storage.get('isScreenFull') || false,
      spinning: false,
      selectAddress: null,
      selectSvgInfo: {},
      infoWaterTemplateVo: {
        bgImg: {},
        addEventGroupDetailForm: [], //分组模板数据
        waterTemplateInfo: [], //普通模板数据
        keyValue: [],
      },
      isShowSelect: '1',
      isShowBackButton: '0',
      showComponentInfoModal: false,
      addressSelecter: [],
      valve_data: {
        0: '关',
        1: '开',
      },
      valve_status: {
        0: '故障',
        1: '正常',
      },
      //阀门状态
      valveStatus: {
        0: 'closeValve',
        1: 'openValve',
      },
      //阀门开关
      switchStatus: {
        0: 'closeValve',
        1: 'openValve',
      },
      switchStatusDict: {
        0: '#FF0000',
        1: '#00FF00',
      },
      clearInfoModalTime: null,
      infoModalData: {},
    }
  },
  created() {
    this.initScreen()
    //监听全屏幕变化
    screenfull.on('change', () => {
      this.initScreen()
    })
  },
  mounted() {
    this.$nextTick(() => {
      let width = document.querySelector('#circuitPreview') ? document.querySelector('#circuitPreview').offsetWidth : undefined
      let homePage = document.querySelector('#homePage')
      let iconScreen = document.querySelector('#iconScreen')
      width && homePage && (homePage.style.transform = 'scale(' + (width / 1920).toFixed(2) + ')')
      width && iconScreen && (iconScreen.style.transform = 'scale(' + (width / 1920).toFixed(2) + ')')
      window.addEventListener('resize', () => {
        let width = document.querySelector('#circuitPreview') ? document.querySelector('#circuitPreview').offsetWidth : undefined
        let homePage = document.querySelector('#homePage')
        let iconScreen = document.querySelector('#iconScreen')
        width && homePage && (homePage.style.transform = 'scale(' + (width / 1920).toFixed(2) + ')')
        width && iconScreen && (iconScreen.style.transform = 'scale(' + (width / 1920).toFixed(2) + ')')
      })
    })

    // 监听窗口变化
    window.addEventListener('resize', () => {
      this.initScreen()
    })
    //请求接口获取组件
    this.$nextTick(() => {
      this.spinning = true
      this.isShowBackButton = this.$route.params.isShowBackButton || '0'
      this.isShowSelect = this.$route.params.isShowSelect || '1'
      //获取地址
      this.$httpRequest(getMachineRoomList, {
        pageSize: -1,
        currPage: -1,
      })
        .then((res) => {
          if (res.records) {
            this.addressSelecter = res.records
            this.previewModel(this.$route.params.waterTemplateId || res.records[0].deviceAreaId)
          }
          if (Storage.get('selectAreaId') && !this.$route.params.waterTemplateId) {
            this.addressSelecter.find((i) => {
              if (i.deviceAreaId === Storage.get('selectAreaId')) {
                this.selectAddress = Storage.get('selectAreaId')
                this.getTemplateList(Storage.get('selectAreaId'))
                return true
              }
            })
            if (!this.selectAddress && this.addressSelecter?.length) {
              this.selectAddress = this.addressSelecter[0].deviceAreaId
              this.getTemplateList(this.selectAddress)
            }
          }
        })
        .catch(() => {
          this.spinning = false
        })
    })
  },
  computed: {
    currentDeviceData() {
      return this.addressSelecter.find((i) => {
        if (i.deviceAreaId === this.selectAddress) {
          return true
        }
      })
    },
  },
  methods: {
    circuitMouseMove(e) {
      const width = this.$refs.circuitPreviewRef.offsetWidth
      const height = this.$refs.circuitPreviewRef.offsetHeight
      let x = e.x,
        y = e.y
      if (width - e.x < 150) x = x - 200
      if (height - e.y < 150) y = y - 200
      // console.log(e.x, width, x)
      this.infoModalData.x = x
      this.infoModalData.y = y
    },
    initScreen() {
      this.$store.setCurrentWindowAttributes({
        height: window.screen.availHeight,
        width: window.screen.availWidth,
        absoluteHeight: window.screen.height,
        absoluteWidth: window.screen.width,
      })
    },
    //全屏
    fullScreenEvent() {
      fullScreen(document.getElementById('circuitPreview')).then((res) => {
        this.isScreenFull = res.status
      })
    },
    //获取新模板
    getTemplateList(id) {
      this.spinning = true
      this.$httpRequest(machineRoomTemplateRendering, {
        deviceAreaId: id,
      })
        .then(async (res) => {
          let infoWaterTemplateVo = {
            addEventGroupDetailForm: res.addEventGroupDetailForm,
            //base64格式图片
            bgImg: {
              base64Data: res.infoWaterTemplateVo.backgroundImg,
              type: res.infoWaterTemplateVo.backgroundImg ? 'normal' : 'default',
            },
            waterTemplateInfo: res.infoWaterTemplateVo.waterTemplateInfo,
            keyData: res.infoWaterTemplateVo.keyData,
          }
          infoWaterTemplateVo.waterTemplateInfo.forEach((item) => {
            item.props = ['prop_data']
            item.defaultAttr = JSON.parse(item.defaultAttr)
          })
          this.infoWaterTemplateVo = this.updateStateValue(infoWaterTemplateVo, infoWaterTemplateVo.keyData)
          this.updateGroupData(this.infoWaterTemplateVo, this.infoWaterTemplateVo.addEventGroupDetailForm)
          this.spinning = false
          message.success('加载成功~')

          this.cwebsocket = new CWebSocket(
            websocketTemplateVoucher,
            'websocket/templateMessage/push/',
            {
              deviceInfoId: this.currentDeviceData.deviceInfoId,
              templateId: this.infoWaterTemplateVo?.waterTemplateInfo[0]?.waterTemplateId,
            },
            this.websocketMessage
          )
        })
        .catch(() => {
          this.spinning = false
        })
    },
    // 更改状态
    updateStateValue(data, keyList) {
      data.componentsState = []
      keyList?.forEach((keyData) => {
        for (const i in data.waterTemplateInfo) {
          let info = data.waterTemplateInfo[i]
          if (keyData.key === info.stateKeyId) {
            // 水管阀
            if (info.type === 'WaterPipeValveSvg') {
              info.defaultAttr.switchs.val.selectval = this.switchStatusDict[keyData.value]
              data.componentsState.push({ componentDataId: info.componentDataId, value: keyData.value })
              info.stateKeyValue = keyData.value
            }
            break
          }
        }
      })
      return data
    },
    // 更改组数据
    updateGroupData(data, addEventGroupDetailForm, parentState = 1) {
      if (parentState == 0) return
      addEventGroupDetailForm.forEach((item) => {
        // 获取当前组的状态
        let stateType = 0
        for (const state of data.componentsState) {
          if (state.componentDataId == item.componentDataId) {
            stateType = state.value
            break
          }
        }
        item.componentsList.forEach((item) => {
          for (const infoItem of data.waterTemplateInfo) {
            if (infoItem.componentDataId === item.componentDataId) {
              infoItem.defaultAttr = stateType == '1' ? JSON.parse(item.openValve) : JSON.parse(item.closeValve)
              break
            }
          }
        })
        // 递归更改子组数据
        if (item.groupLists?.length) {
          this.updateGroupData(data, item.groupLists, stateType)
        }
      })
    },
    // 获取websocket传过来的数据
    websocketMessage(data) {
      data = JSON.parse(data)
      this.infoWaterTemplateVo.keyData.forEach(i => {
        data.find(j => {
          if (j.key === i.key) {
            i.value = j.value
            return true
          }
        })
      })
      if (!this.infoWaterTemplateVo?.keyData?.length) {
        this.getTemplateList()
      }else{
        this.updateStateValue(this.infoWaterTemplateVo, data)
        this.updateGroupData(this.infoWaterTemplateVo, this.infoWaterTemplateVo.addEventGroupDetailForm)
      }
    },
    // isScreenFullEvent(val) {
    //   Storage.set('isScreenFull', val);
    //   window.parent.postMessage({ type: 'screenFull', data: val }, '*');
    //   this.isScreenFull = Storage.get('isScreenFull');
    // },
    previewModel(id) {
      this.spinning = true
      this.$httpRequest(infoTemplate, {
        waterTemplateId: id,
      })
        .then((res) => {
          res.data.waterTemplateInfo.forEach((item) => {
            item.props = ['prop_data']
            item.defaultAttr = JSON.parse(item.defaultAttr)
          })
          this.infoWaterTemplateVo.bgImg = {
            base64Data: res.data.backgroundImg,
            type: res.data.backgroundImg ? 'normal' : 'default',
          }
          this.infoWaterTemplateVo.waterTemplateInfo = res.data.waterTemplateInfo
          this.spinning = false
          message.success('加载成功~')
        })
        .catch(() => {
          this.spinning = false
        })
    },
    changeSelect(id) {
      this.getTemplateList(id)
      Storage.set('selectAreaId', id)
    },
    showComponentInfoModalMethod(val, e) {
      this.showComponentInfoModal = val
      if (val) {
        const componentInfoModal = this.$refs.componentInfoModal
        if (componentInfoModal) {
          componentInfoModal.style.left = this.infoModalData.x + 'px'
          componentInfoModal.style.top = this.infoModalData.y + 'px'
        }
      }
    },
    mouseoverSvg(e, index) {
      clearTimeout(this.clearInfoModalTime)
      const componentData = this.infoWaterTemplateVo.waterTemplateInfo[index]
      if (!this.infoWaterTemplateVo.keyData) this.infoWaterTemplateVo.keyData = []
      const keyData = this.infoWaterTemplateVo.keyData?.filter((i) => {
        return i.key === componentData.stateKeyId || i.key === componentData.dataKeyId
      })
      this.selectSvgInfo = { componentData, keyData }
      console.log(this.selectSvgInfo)
      this.showComponentInfoModalMethod(true, e)
    },
    clearSelectSvgInfo(e) {
      this.clearInfoModalTime = setTimeout(() => {
        clearTimeout(this.clearInfoModalTime)
        this.selectSvgInfo = {}
        this.showComponentInfoModal = false
      }, 200)
    },
    returnRouter() {
      this.$router.back(-1)
    },
  },
  unmounted() {
    this.cwebsocket && this.cwebsocket.manualClose()
  },
}
</script>
<style scoped lang="less">
#circuitPreview {
  background-color: #000d26;
  overflow: hidden;
  position: relative;
}
.layout {
  width: 100% !important;
  transform-origin: 0 0 0;
}
.btns-content {
  position: fixed;
  left: 10px;
  bottom: 80px;
  button {
    margin-right: 10px;
  }
}
.cursor:hover {
  cursor: pointer;
}
.topo-layer-view-selected {
  outline: 1px solid #0cf;
}
.componentInfoModal {
  pointer-events: none;
  min-width: 200px;
  min-height: 100px;
  color: white;
  position: absolute;
  z-index: 99999;
  background: rgba(6, 50, 125, 0.5);
  padding: 5px;
  margin: 0px;
  display: block;
  border-radius: 5px;
  .title {
    text-align: center;
  }
}
.selectAddress {
  position: fixed;
  top: 10px;
  left: 10px;
}
.svg-contain {
  background-size: cover;
  -webkit-transform-origin: top left;
  transform-origin: top left;
  // overflow: auto;
}
.svgContent {
  height: 100%;
  width: 100%;
}
.emptyCenter {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}
.screen {
  cursor: pointer;
  width: 100px;
  position: fixed;
  right: 30px;
  top: 10px;
  text-align: right;
  div {
    color: #4a98dc;
    font-size: 25px;
  }
}
</style>
